/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import cn.webrx.pojo.Student;
import cn.webrx.pojo.Teacher;
import cn.webrx.pojo.User;
import cn.webrx.services.Db;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;
import java.util.Date;

/**
 * <p>Project: spring2022 - DruidConfig
 * <p>Powered by webrx On 2022-03-17 16:03:58
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */

@PropertySource("db.properties")  //加载配置文件resources/db.properties 文件
public class DruidConfig {

    @Value("${db.url}")
    private String url;
    @Value("${db.username}")
    private String username;

    @Bean("tt")
    public Date now() {
        return new Date();
    }

    //@Bean @Scope("prototype")
    public DataSource ds() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl("jdbc:mysql://localhost:3306/db");
        ds.setUsername("root");
        return ds;
    }

    @Bean(name = "ds2", initMethod = "init", destroyMethod = "close")
    public DruidDataSource ds2() {
        DruidDataSource ds = new DruidDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        return ds;
    }

    //@Bean
    public QueryRunner run2(@Qualifier("ds") DataSource dsabc) {//指定相关的名称进行装配
        QueryRunner run = new QueryRunner(dsabc);
        return run;
    }

    @Bean
    public QueryRunner run(DataSource a) { //此处的DateSource a 是自动装配置，如果容器中有多个会报错
        QueryRunner run = new QueryRunner(a);
        return run;
    }


    @Bean("wu")
    @Scope("prototype")
    public User getUser() {
        User u = new User();
        u.setId(100);
        u.setName("王五");
        return u;
    }

    @Bean
    public Teacher lisi() {
        Teacher t = new Teacher();
        t.setId(11);
        t.setTname("李四老师");
        return t;
    }

    @Bean
    public Student zs(@Qualifier("lisi") Teacher t, @Value("${db.username}") String name) {
        Student s = new Student();
        s.setId(111);
        s.setName(name);
        s.setTeacher(t);
        return s;
    }


    @Bean(initMethod = "init", destroyMethod = "close")
    public Db db() {
        Db db = new Db();
        return db;
    }


}
